const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { verifyToken } = require('../middleware/auth');
const { formatResponse } = require('../utils/response');

// 创建订单
router.post('/', verifyToken, async (req, res) => {
  try {
    const userId = req.userId;
    const totalAmount = 0.5;
    const connection = await pool.getConnection();
    const { mhid, mhsuiji } = req.body;

    try {
      await connection.beginTransaction();
      // 创建订单
      const [orderResult] = await connection.execute(
        'INSERT INTO orders (userId,mhid,mhsuiji,totalAmount,status,createdAt) VALUES (?, ?, ?, ?, ?, NOW())',
        [userId, mhid, mhsuiji, totalAmount, 'pending']
      );
      const orderId = orderResult.insertId;
      await connection.commit();
      res.json(formatResponse(200, '订单创建成功', { orderId }));
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    res.status(500).json(formatResponse(500, '创建订单失败', error.message));
  }
});

// 获取订单列表 - 支持按用户ID和订单状态筛选
router.get('/', verifyToken, async (req, res) => {
  try {
    // 从认证中间件获取当前用户ID（确保数据访问权限）
    const userId = req.userId;
    // 从查询参数获取订单状态（可选筛选条件）
    const { status } = req.query;

    // 构建基础查询和参数数组
    let query = 'SELECT * FROM orders WHERE userId = ?';
    const queryParams = [userId];

    // 如果提供了状态参数，则添加到查询条件
    if (status) {
      query += ' AND status = ?';
      queryParams.push(status);
    }

    // 按创建时间降序排列，最新订单在前
    query += ' ORDER BY createdAt DESC';

    // 执行查询并返回结果
    const [orders] = await pool.execute(query, queryParams);
    res.json(formatResponse(200, '订单列表获取成功', orders));
  } catch (error) {
    res.status(500).json(formatResponse(500, '获取订单列表失败', error.message));
  }
});

// 更改订单
router.put('/:status/:id', verifyToken, async (req, res) => {
  try {
    const orderId = req.params.id; // 从路径获取订单ID
    const status = req.params.status; // 从路径获取订单状态

    // 直接更新订单状态为取消
    const [result] = await pool.execute(
      'UPDATE orders SET status = ?, updatedAt = NOW() WHERE id = ?',
      [status, orderId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json(formatResponse(404, '订单不存在'));
    }

    res.json(formatResponse(200, '订单修改成功'));
  } catch (error) {
    res.status(500).json(formatResponse(500, '订单修改失败', error.message));
  }
});

module.exports = router;